<template>
  <!-- 系统管理 -->
  <div class="app-container">
    <div class="mainbox">
      <!-- 顶部操作 -->
      <div class="filter-container">
        <el-form ref="filterFormRef" :inline="true" :model="filterForm">
          <el-form-item label="企业名称:" prop="companyName">
            <el-input
              v-model.trim="filterForm.companyName"
              class="filter-item limit"
              style="width: 200px;margin-right:10px"
              maxlength="30"
              clearable
              placeholder="请输入姓名"
              @keyup.enter.native="$_handleFilter"
            />
          </el-form-item>
          <el-form-item label="收录状态:" prop="status">
            <el-select v-model.trim="filterForm.status" placeholder="请选择" :clearable="true">
              <el-option
                v-for="item in [{value: 1,label:'已收录'}, {value: 0,label:'未收录'}]"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="数据来源:" prop="source">
            <el-select v-model.trim="filterForm.source" placeholder="请选择" :clearable="true">
              <el-option
                v-for="dict in dict.type.zs_sjly"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="采集时间:" prop="times">
            <el-date-picker
              v-model="filterForm.times"
              type="datetimerange"
              :picker-options="pickerOptions"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="yyyy-MM-dd HH:mm:ss"
              value-format="yyyy-MM-dd HH:mm:ss"
              align="right">
            </el-date-picker>
          </el-form-item>
        </el-form>
        <div class="flex-1" />
        <el-button type="primary" @click="$_handleFilter">查询</el-button>
        <el-button @click="$_handleReset">重置</el-button>

      </div>
      <!-- 表格 -->
      <div class="table-container table-fullscreen">
        <div class="table-opt-container">
          <el-button
            v-permission="['CLUEDATA_ADD_BUTTON']"
            type="primary"
            icon="el-icon-plus"
            @click="handleAdd"
          >
            新增
          </el-button>
          <el-button
            v-permission="['CLUEDATA_IMPORT_BUTTON']"
            icon="el-icon-folder-add"
            type="primary"
            @click="$_handleImport()"
          >
            导入
          </el-button>
          <el-button
            v-permission="['CLUEDATA_EXPORT_BUTTON']"
            icon="el-icon-folder-remove"
            type="primary"
            @click="handleExport()"
          >
            导出
          </el-button>
          <el-button
            v-permission="['CLUEDATA_CLAIM_BUTTON']"
            icon="el-icon-folder-add"
            type="primary"
            @click="handleClaim"
          >
            认领
          </el-button>
          <el-button
            v-if="!!userZBInfo && userZBInfo.type === '1'"
            v-permission="['CLUEDATA_GIVE_BUTTON']"
            icon="el-icon-folder-remove"
            type="primary"
            @click="openFFPop"
          >
            分发
          </el-button>
          <div class="flex-1" />
          <dt-dialog-column :columns="columns" @queryTable="getList" />
        </div>
        <el-table
          ref="table"
          v-loading="MX_listLoading"
          :data="MX_list"
          border
          highlight-current-row
          :row-key="$_getRowKey"
          style="width: 100%;text-align:center"
          :header-cell-style="MX_headerCellStyle"
          @selection-change="$_handleSelectionChange"
        >
          <template slot="empty">
            <p>暂无数据！</p>
          </template>
          <el-table-column
            type="selection"
            width="55"
            :selectable='selectable'>
          </el-table-column>
          <el-table-column
            fixed="left"
            type="index"
            label="序号"
            width="70"
            align="center"
            :index="$_tableIndex"
          />
          <el-table-column
            v-for="item in columns"
            :key="item.prop"
            :prop="item.prop"
            :label="item.label"
            :width="item.width"
            :min-width="item.minWidth"
            :formatter="item.formatter"
            align="center"
          />
          <el-table-column
            :key="Math.random()"
            fixed="right"
            label="操作"
            width="260px"
            align="center"
          >
            <template slot-scope="scope">
              <el-button
                size="mini"
                class="tBtn"
                @click="newWid(scope.row[idKeyName])"
              >企业画像</el-button>
              <el-button
                v-if="!scope.row.status"
                v-permission="['CLUEDATA_RECRUIT_BUTTON']"
                size="mini"
                class="tBtn"
                type="primary"
                @click="handleEmploy(scope.row)"
              >收录</el-button>
              <el-button
                v-if="!scope.row.status"
                v-permission="['CLUEDATA_DEL_BUTTON']"
                size="mini"
                type="danger"
                class="tBtn"
                @click="handleDelete(scope.row[idKeyName])"
              >删除</el-button>
              <el-button
                v-if="!!scope.row.status"
                size="mini"
                class="tBtn"
                @click="goto(`intserv/InvestmentActivity?id=${scope.row[idKeyName]}`)"
              >招商活动</el-button>
              <el-button
                v-if="scope.row.source == 4"
                size="mini"
                class="tBtn"
                @click="goto(`dataCapture/Livejournal?name=${scope.row.companyName}`)"
              >意向信息</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页器 -->
        <dt-pagination
          v-show="MX_total > 0"
          :total="MX_total"
          :page.sync="MX_pageNav.pageNo"
          :limit.sync="MX_pageNav.pageSize"
          @pagination="getList"
        />
      </div>
      <DialogForm ref="dialogForm" labelWidth="140px" :formDesignList="formDesignList" />
      <dtDialog
        title="导入"
        class="get-page-form-import-dialog"
        :visible.sync="MX_fileUploadVisible"
        width="620px"
        :is-loading="MX_uploadLoading"
        @closeDialog="MX_fileUploadVisible = false"
        @comfirmBtn="$_importDataSave(importApi)"
      >
        <el-form slot="content">
          <div class="">
            <dt-importFile ref="dtImportFileRef" :down-load-template="handleImportTemplate" :type="fileName" />
          </div>
        </el-form>
      </dtDialog>
    </div>
    <dtDialog title="线索分发" :visible.sync="isOpenFFPop" width="450px" @comfirmBtn="handleFF()">
      <div class="demo-input-suffix">
        分发人员：
        <el-select style="width: calc(100% - 90px);" v-model.trim="choiceFFUserId" placeholder="请选择" :clearable="true">
          <el-option
            v-for="item in userZBList"
            :key="item.userId"
            :label="item.userName"
            :value="item.userId"
          />
        </el-select>
      </div>
    </dtDialog>
  </div>
</template>
<script>
import DialogForm from '@/views/investment/components/DialogForm'
import commonList from "@/utils/mixins/investment/commonList";
import dataCaptureApi from "@/api/investment/dataCapture";
import {parseTime} from "@/framework/utils/date";
import systemApi from "@/api/investment/system";

export default {
  dicts: ['zs_sjly'],
  name: 'ClueData',
  components: {
    DialogForm
  },
  mixins: [commonList],
  data() {
    const _this = this
    return {
      filterForm: {
        companyName: '',
        status: '',
        source: '',
        times: ''
      },
      fileName: '线索数据导入',
      handleImportTemplate: dataCaptureApi.exportXS,
      importApi: dataCaptureApi.importXS,
      // 列信息
      columns: [
        { prop: 'companyName', label: `企业名称`, minWidth: '150px' },
        { prop: 'isYang', label: `是否央企`, width: '100px', formatter: function(row) {
            return row.isYang === 1 ? '是' : '否'
          } },
        { prop: 'userName', label: `管理人员`, width: '130px' },
        { prop: 'managTime', label: `开始管理时间`, width: '180px', formatter: function(row) {
            return !!row.managTime ? parseTime(new Date(row.managTime)) : ''
          } },
        { prop: 'source', label: `数据来源`, width: '120px', formatter: (row) => {
            return _this.dict.label.zs_sjly[row.source]
          } },
        { prop: 'collectionTime', label: `采集时间`, width: '180px', formatter: (row) => {
            return !!row.collectionTime ? parseTime(new Date(row.collectionTime)) : ''
          } },
        { prop: 'specialized', label: `收录专班`, width: '120px', formatter: (row) => {
          let item = _this.zbList.filter(v => v.value === row.specializedId)
            return item.length ? item[0].label : ''
          } },
        { prop: 'status', label: `收录状态`, width: '100px', formatter: function(row) {
            return row.status === 1 ? '已收录' : '未收录'
          } }
      ],
      formDesignList: [
        { type: 'text', prop: 'companyName', label: `企业名称`, rules: [{ required: true, message: '请输入企业名称', trigger: 'blur' }] },
        { type: 'switch', prop: 'isYang', label: `是否央企`, onVal: 1, offVal: 0, defaultVal: 0, rules: [{ required: true, message: '请选择是否央企', trigger: 'change' }] },
        { type: 'select', prop: 'source', label: `数据来源`, dictTypeCode: 'zs_sjly', disabledList: ['2', '4'], rules: [{ required: true, message: '请选择数据来源', trigger: 'change' }] },
        { type: 'datetime', prop: 'collectionTime', label: `采集时间`, format: 'yyyy-MM-dd HH:mm:ss', rules: [{ required: true, message: '请选择采集时间', trigger: 'blur' }] },
        { type: 'select', prop: 'specializedId', label: `收录专班`, dictOptions: [], rules: [{ required: true, message: '请选择收录专班', trigger: 'change' }] },
        { type: 'switch', prop: 'status', label: `收录状态`, onVal: 1, offVal: 0, defaultVal: 1, readonly: true, rules: [{ required: true, message: '请选择收录状态', trigger: 'change' }] },
      ],
      idKeyName: 'id',
      userZBInfo: null,
      userZBList: [],
      zbList: [],
      FFUserList: [],
      choiceFFUserId: null,
      isOpenFFPop: false,
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      }
    }
  },
  watch: {
    'filterForm.times'(val) {
      this.$set(this.filterForm, 'start', !!val ? val[0] : '')
      this.$set(this.filterForm, 'end', !!val ? val[1] : '')
    },
    zbList(val){
      this.$set(this.formDesignList[4], 'dictOptions', val)
    },
    isOpenFFPop(val){
      if (!!val) this.choiceFFUserId = null
    }
  },
  created() {
    this.getList()
    this.getZBList()
    this.getUserZBInfo()
    this.zbList = []
  },
  methods: {
    selectable(row){
      return !!this.userZBInfo && row.specializedId === this.userZBInfo.specializedId
    },
    getZBList(){
      systemApi.getZBList({pageSize: -1}).then(res => {
        let list = res.data.rows || [];
        this.zbList = list.map(v => {
          v.value = v.id
          v.label = v.groupName
          return v
        })
      })
    },
    getUserZBInfo(){
      dataCaptureApi.getUserOfZB().then(res => {
        this.userZBInfo = res.data
        if (this.userZBInfo.type === '1'){
          this.getUserZBList()
        }
        if(!!this.userZBInfo.specializedId) {
          this.$set(this.formDesignList[4], 'defaultVal', this.userZBInfo.specializedId)
          this.$set(this.formDesignList[4], 'disabled', true)
        }
      })
    },
    getUserZBList(){
      systemApi.detailZBItem({id: this.userZBInfo.specializedId}).then(res => {
        let list = res.data.groupIndexUsers || [];
        this.userZBList = list
      })
    },
    // 获取页面列表
    getList() {
      let filterForm = JSON.parse(JSON.stringify(this.filterForm))
      delete filterForm.times
      this.MX_listLoading = true
      dataCaptureApi.getXSList({
        ...filterForm,
        ...this.MX_pageNav
      }).then((res) => {
        this.MX_listLength = res.data.records.length
        this.MX_list = res.data.records
        this.MX_total = parseInt(res.data.total || '0')
        this.MX_listLoading = false
      })
    },
    //收录
    handleEmploy(data){
      const loading = this.$loading({
        lock: true, text: ``, spinner: 'el-icon-loading', background: 'rgba(0, 0, 0, 0.7)'
      })
      dataCaptureApi.employXSItem({
        [this.idKeyName]: data[this.idKeyName]
      }).then(res => {
        loading.close()
        if (res.code == '00000') {
          this.$dtMessage({
            type: 'success',
            message: '收录成功'
          })
          this.getList()
        }else{
          this.$dtMessage({
            type: 'error',
            message: res.message || '收录失败'
          })
        }
      }).catch(e => {
        loading.close()
      })
    },
    multiCheckedValue(msg){
      if (!this.MX_multipleSelection.length) {
        this.$dtMessageBox({title: '提示', message: `请选择需要进行批量${msg}的数据！`, type: 'warning'})
        return false
      }
      let ids = this.MX_multipleSelection.map(v => {
        return v[this.idKeyName]
      })
      return ids
    },
    //认领
    handleClaim(){
      const msg = '认领'
      const ids = this.multiCheckedValue(msg)
      if (!ids) return
      this.postApi('claimXSItem', ids, msg)
    },
    //分发
    openFFPop(){
      const ids = this.multiCheckedValue('分发')
      if (!ids) return
      this.isOpenFFPop = true
    },
    handleFF(){
      if (!this.choiceFFUserId){
        this.$dtMessage({
          type: 'error',
          message: `请选择分发用户！`
        })
        return;
      }
      const msg = '分发'
      const ids = this.multiCheckedValue(msg)
      const choiceFFUserInfo = this.userZBList.filter(v => v.userId === this.choiceFFUserId)[0]
      this.postApi('ffXSItem', {ids, userId: choiceFFUserInfo.userId, userName: choiceFFUserInfo.userName || ''}, msg, () => {
        this.isOpenFFPop = false
      })
    },
    postApi(apiName, params, msg, callBack){
      const loading = this.$loading({
        lock: true, text: ``, spinner: 'el-icon-loading', background: 'rgba(0, 0, 0, 0.7)'
      })
      dataCaptureApi[apiName](params).then(res => {
        loading.close()
        if (res.code == '00000') {
          this.$dtMessage({
            type: 'success',
            message: `${msg}成功`
          })
          this.getList()
          if (!!callBack) callBack()
        }else{
          this.$dtMessage({
            type: 'error',
            message: res.message || `${msg}失败`
          })
        }
      }).catch(e => {
        loading.close()
      })
    },
    // 添加按钮
    handleAdd() {
      this.$refs.dialogForm.open('add', dataCaptureApi.addXSItem)
    },
    // 删除按钮
    handleDelete(id) {
      this.$_handleDelete(dataCaptureApi.delXSItem, id, this.idKeyName)
    },
    /** 导出按钮操作 */
    handleExport() {
      this.$_handleDownload(dataCaptureApi.exportXS, '线索数据', {type: 1, ...this.filterForm}, '导出');
    },
    goto(url){
      this.$router.push(`/investment/${url}`)
    },
    newWid(id){
      const routeData = this.$router.resolve({ name: 'BusinessPortraits' });
      window.open(`${routeData.href}?id=${id}`, '_blank');
    }
  }
}
</script>

<style lang="scss" scoped>
.tBtn{
  margin-top: 3px;
  margin-bottom: 3px;
}
</style>
